package logic

import (
	"context"
	"fmt"
	"house/models/cache"
	"house/models/mysql"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetLogic {
	return &ForgetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetLogic) Forget(in *houserpc.ForgetRequest) (*houserpc.ForgetResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当期账号不存在")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "send"+in.Mobile).Result()
	if in.SendSms != result {
		return nil, fmt.Errorf("验证码错误")
	}
	if user.Password == in.Password {
		return nil, fmt.Errorf("旧密码与新密码一样")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次输入密码不一致")
	}
	user.Password = in.Password
	mysql.DB.Debug().Updates(&user)
	return &houserpc.ForgetResponse{
		UserId: int64(user.ID),
	}, nil
}
